package com.wyh.service.serviceImpl.groupOne.titleReview;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wyh.common.exception.CustomException;
import com.wyh.common.result.Result;
import com.wyh.domain.po.groupOne.titleReview.MasterDataCustomer;
import com.wyh.domain.po.groupOne.titleReview.MasterDataInvoiceheader;
import com.wyh.domain.vo.groupOne.titleReview.GetInvoiceheaderVO;
import com.wyh.domain.vo.groupOne.titleReview.MasterDataInvoiceheaderVO_2;
import com.wyh.mapper.groupOne.titleReview.MasterDataInvoiceheaderMapper;
import com.wyh.service.groupOne.titleReview.MasterDataICustomerService;
import com.wyh.service.groupOne.titleReview.MasterDataIInvoiceheaderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.wyh.common.enums.ResultCodeEnum.*;

/**
 * <p>
 * 发票抬头表 服务实现类
 * </p>
 *
 * @author lsf
 * @since 2024-05-28
 */
@Service
@Slf4j
public class MasterDataInvoiceheaderServiceImplMasterData extends ServiceImpl<MasterDataInvoiceheaderMapper, MasterDataInvoiceheader> implements MasterDataIInvoiceheaderService {
    @Autowired
    private MasterDataICustomerService customerService;
    @Autowired
    private MasterDataInvoiceheaderMapper masterDataInvoiceheaderMapper;

    /**
     * 查询发票抬头表
     * @param getInvoiceheaderVO
     * @return
     */
    @Override
    public Result<List<MasterDataInvoiceheaderVO_2>> getAudit(GetInvoiceheaderVO getInvoiceheaderVO) {
        //判断是否有state
        if (getInvoiceheaderVO.getState()==null){
            return Result.error(PARAM_ERROR);
        }

        MasterDataCustomer masterDataCustomerFind =new MasterDataCustomer();

        BeanUtils.copyProperties(getInvoiceheaderVO, masterDataCustomerFind);

        //模糊查询客户表

        QueryWrapper<MasterDataCustomer> customerQueryWrapper=new QueryWrapper<MasterDataCustomer>()
                .select("id","name","telephone");
                if (getInvoiceheaderVO.getName()!=null){
                    customerQueryWrapper.like("name", masterDataCustomerFind.getName());
                }
                if (getInvoiceheaderVO.getTelephone()!=null){
                    customerQueryWrapper.like("telephone", masterDataCustomerFind.getTelephone());
                }




        List<MasterDataCustomer> masterDataCustomerList = customerService.list(customerQueryWrapper);
        log.info("masterDataCustomerList:{}", masterDataCustomerList);

        //获取符合的用户IdList
        List<Integer> customerIdList = masterDataCustomerList.stream()
                .map(MasterDataCustomer::getId)
                .collect(Collectors.toList());
        log.info("customerIdList:{}",customerIdList);

        //发票抬头表查询
        QueryWrapper<MasterDataInvoiceheader> invoiceheaderQueryWrapper=new QueryWrapper<MasterDataInvoiceheader>();
        if (customerIdList!=null&&customerIdList.size()>0){
            invoiceheaderQueryWrapper.in("customerid",customerIdList);
        }
        if (getInvoiceheaderVO.getBuyername()!=null){
            invoiceheaderQueryWrapper.like("buyername",getInvoiceheaderVO.getBuyername());
        }

            invoiceheaderQueryWrapper.eq("state",getInvoiceheaderVO.getState());

        if (getInvoiceheaderVO.getFindingsofaudit()!=null){
            invoiceheaderQueryWrapper.eq("findingsofaudit",getInvoiceheaderVO.getFindingsofaudit());

        }


        //String转LocalTime
        DateTimeFormatter localDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        try {


            if (getInvoiceheaderVO.getApplicationtimeLowerlimit()!=null) {

                LocalDateTime applicationtimeLowerlimit = LocalDateTime.parse(getInvoiceheaderVO.getApplicationtimeLowerlimit(), localDateTimeFormatter);
                invoiceheaderQueryWrapper.ge("applicationtime",applicationtimeLowerlimit);
            }
            if (getInvoiceheaderVO.getApplicationtimeUpperlimit()!=null) {

                LocalDateTime applicationtimeUpperlimit = LocalDateTime.parse(getInvoiceheaderVO.getApplicationtimeUpperlimit(), localDateTimeFormatter);
                invoiceheaderQueryWrapper.le("applicationtime",applicationtimeUpperlimit);
            }
            if (getInvoiceheaderVO.getTimeLowerlimit()!=null) {


                LocalDateTime timeLowerlimit = LocalDateTime.parse(getInvoiceheaderVO.getTimeLowerlimit(), localDateTimeFormatter);
                invoiceheaderQueryWrapper.ge("time",timeLowerlimit);
            }
            if (getInvoiceheaderVO.getTimeUpperlimit()!=null) {

                LocalDateTime timeUpperlimit = LocalDateTime.parse(getInvoiceheaderVO.getTimeUpperlimit(), localDateTimeFormatter);
                invoiceheaderQueryWrapper.le("time",timeUpperlimit);
            }
        }catch (Exception e){
            return Result.error(INPUT_RULE_ERROR);
        }

        Page<MasterDataInvoiceheader> invoiceheaderPage=page(new Page<>(getInvoiceheaderVO.getCurrentPage(),getInvoiceheaderVO.getSize()),invoiceheaderQueryWrapper);
        List<MasterDataInvoiceheader> masterDataInvoiceheaderList =invoiceheaderPage.getRecords();
        log.info("------masterDataInvoiceheaderList:{}", masterDataInvoiceheaderList);
        //返回数据
        List<MasterDataInvoiceheaderVO_2> masterDataInvoiceheaderVO2List = new ArrayList<>();
        for (int i = 0; i< masterDataInvoiceheaderList.size(); i++){
            MasterDataInvoiceheaderVO_2 masterDataInvoiceheaderVO2Copy =new MasterDataInvoiceheaderVO_2();
            BeanUtils.copyProperties(masterDataInvoiceheaderList.get(i), masterDataInvoiceheaderVO2Copy);
            /**
             * 二分查找name和Telephone
             */
            for (int low = 0, high = masterDataCustomerList.size()-1; low<=high;){
                int mid=(low+high)/2;
                if (Objects.equals(masterDataCustomerList.get(mid).getId(), masterDataInvoiceheaderList.get(i).getCustomerid())){
                    masterDataInvoiceheaderVO2Copy.setName(masterDataCustomerList.get(mid).getName());
                    masterDataInvoiceheaderVO2Copy.setTelephone(masterDataCustomerList.get(mid).getTelephone());
                    break;

                } else if (masterDataCustomerList.get(mid).getId()> masterDataInvoiceheaderList.get(i).getCustomerid()) {

                    high=mid-1;
                }
                else {

                    low=mid+1;
                }

            }
            if (masterDataInvoiceheaderVO2Copy.getName()==null|| masterDataInvoiceheaderVO2Copy.getTelephone()==null){
                throw new CustomException(SYSTEM_ERROR);
            }
            masterDataInvoiceheaderVO2Copy.setTotal(invoiceheaderPage.getTotal());
            masterDataInvoiceheaderVO2List.add(masterDataInvoiceheaderVO2Copy);
        }
        log.info("------masterDataInvoiceheaderVO2List:{}", masterDataInvoiceheaderVO2List);


        return Result.success(masterDataInvoiceheaderVO2List);
    }

    /**
     * (目标参数):通过该发票(1),驳回该发票(2),撤销该发票审核(0)
     * @param masterDataInvoiceheaderVO2
     * @return
     */

    @Override
    public Result auditing(MasterDataInvoiceheaderVO_2 masterDataInvoiceheaderVO2, int target) {
        //参数合理性判断
        if (masterDataInvoiceheaderVO2.getFindingsofaudit()!=0&&(target==1||target==2)){
            return Result.error(PARAM_ERROR);
        }
       else if (masterDataInvoiceheaderVO2.getFindingsofaudit()==0&&target==0){
            return Result.error(PARAM_ERROR);
        }



        UpdateWrapper<MasterDataInvoiceheader> invoiceheaderUpdateWrapper=new UpdateWrapper<MasterDataInvoiceheader>()
                .set("findingsofaudit",target)
                .set("state",(target!=0) ? 1:0)
                .eq("id", masterDataInvoiceheaderVO2.getId());


            boolean update = update(invoiceheaderUpdateWrapper);
                if (update){
                    System.out.println("修改成功:target:"+target);
                }
                else {
                    System.out.println("修改失败:target:"+target);
                    return Result.error(PARAM_ERROR);
                }


        return Result.success();
    }



    /**
     * 判断对象中是否存在空值
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public boolean checkObjFieldIsNull(Object obj) throws IllegalAccessException {
        boolean flag = false;
        for(Field f : obj.getClass().getDeclaredFields()){
            f.setAccessible(true);
            log.info(f.getName());
            if(f.get(obj) == null){
                flag = true;
                return flag;
            }
        }
        return flag;
    }
}
